﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YiSha.Entity.SystemManage;
using YiSha.Enums;
using YiSha.Model.Result;
using YiSha.Util;
using YiSha.Util.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using YiSha.Service.SystemManage;
using YiSha.Service.OrganizationManage;
using YiSha.Basics;
using YiSha.Framework;
using YiSha.Entity.OrganizationManage;
using YiSha.MemoryCache;
using YiSha.Cache.Factory;
using YiSha.Business.Cache;

namespace YiSha.Admin.Web.Controllers
{
    public class HomeController : BaseController
    {
        /// <summary>
        /// 用户服务
        /// </summary>
        public UserService userService { get; set; }
        /// <summary>
        /// 菜单服务
        /// </summary>
        public MenuService menuService { get; set; }
        /// <summary>
        /// 登录日志服务
        /// </summary>
        public LogLoginService logLoginService { get; set; }
        public MenuAuthorizeService menuAuthorize { get; set; }
        public IWebHostEnvironment WebHostEnvironment;
        public HomeController(IWebHostEnvironment webHostEnvironment)
        {
            WebHostEnvironment = webHostEnvironment;
        }
        #region 视图功能
        [HttpGet]
        [AuthorizeFilter]
        public async Task<IActionResult> Index()
        {
            OperatorInfo operatorInfo = await OperatorService.Instance.Current();
            //获取菜单列表
            var objMenu = await menuService.GetList(null);
            var menuList = objMenu.Data;
            //排除禁用菜单
            menuList = menuList.Where(p => p.MenuStatus == StatusEnum.Yes.ParseToInt()).ToList();

            if (operatorInfo.IsSystem != 1)
            {
                TData<List<MenuAuthorizeInfo>> objMenuAuthorize = await menuAuthorize.GetAuthorizeList(operatorInfo);
                List<string> authorizeMenuIdList = objMenuAuthorize.Data.Select(p => p.MenuId).ToList();
                menuList = menuList.Where(p => authorizeMenuIdList.Contains(p.Id)).ToList();
            }

            ViewBag.MenuList = menuList;
            ViewBag.OperatorInfo = operatorInfo;
            return View();
        }
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Welcome()
        {
            return View();
        }
        #region 锁屏
        /// <summary>
        /// 锁屏
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult LockScreen()
        {
            var info = OperatorService.Instance.Current().Result;
            //获取缓存
            var cache = CacheFactory.Cache.GetCache<OperatorInfo>("lockScreenUser_" + info.UserId);
            if (!cache.IsEmpty())
            {
                CacheFactory.Cache.SetCache("lockScreenUser_" + info.UserId, info);
                ViewBag.name = info.UserName;
                ViewBag.avatar = info.Portrait;
            }
            
            return View();
        }
        /// <summary>
        /// 解锁屏幕
        /// </summary>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public async Task<IActionResult> UnlockScreen(string password)
        {
            var obj = new TData();
            var info = OperatorService.Instance.Current();
            //获取当前登录用户信息
            TData<UserEntity> userInfo = await userService.GetUser(info.Result.UserId);
            //
            var user = userInfo.Data as UserEntity;
            if (user.IsEmpty())
            {
                obj.Msg = "当前用户不存在";
                obj.MsgCode = MsgCode.Fail;
                return Json(obj);
            }
            if (user.Password != userService.EncryptUserPassword(password, user.Salt))
            {
                obj.Msg = "密码错误";
                obj.MsgCode = MsgCode.Fail;
                return Json(obj);
            }
            //解锁移除缓存
            var cache = CacheFactory.Cache.GetCache<OperatorInfo>("lockScreenUser_" + user.Id);
            if (!cache.IsEmpty())
            {
                CacheFactory.Cache.RemoveCache("lockScreenUser_" + info.Result.UserId);
            }
            return Json(obj);
        }
        #endregion


        [HttpGet]
        public IActionResult Login()
        {
            if (WebHostEnvironment.IsDevelopment())
            {
                ViewBag.UserName = "admin";
                ViewBag.Password = "123456";
            }
            if (HttpContext.Session.GetString("errorCodeNum") == null)
            {
                ViewBag.ErrorNum = 0;
                HttpContext.Session.SetString("errorCodeNum", "0");
            }
            else
            {
                ViewBag.ErrorNum = int.Parse(HttpContext.Session.GetString("errorCodeNum"));
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> LoginOff()
        {
            #region 退出系统
            OperatorInfo user = await OperatorService.Instance.Current();
            if (user != null)
            {
                // 如果不允许同一个用户多次登录，当用户登出的时候，就不在线了
                if (!GlobalContext.SystemConfig.LoginMultiple)
                {
                    //await userBLL.UpdateUser(new UserEntity { Id = user.UserId, IsOnline = 0 });
                }

                // 登出日志
                //await logLoginBLL.SaveForm(new LogLoginEntity
                //{
                //    LogStatus = OperateStatusEnum.Success.ParseToInt(),
                //    Remark = "退出系统",
                //    IpAddress = NetHelper.Ip,
                //    IpLocation = string.Empty,
                //    Browser = NetHelper.Browser,
                //    OS = NetHelper.GetOSVersion(),
                //    ExtraRemark = NetHelper.UserAgent,
                //    BaseCreatorId = user.UserId
                //});

                OperatorService.Instance.RemoveCurrent();
                new CookieHelper().RemoveCookie("RememberMe");
            }
            if (WebHostEnvironment.IsDevelopment())
            {
                ViewBag.UserName = "admin";
                ViewBag.Password = "123456";
            }
            #endregion
            return View(nameof(Login));
        }

        [HttpGet]
        public IActionResult NoPermission()
        {
            return View();
        }

        [HttpGet]
        public IActionResult Error(string message)
        {
            ViewBag.Message = message;
            return View();
        }

        [HttpGet]
        public IActionResult Skin()
        {
            return View();
        }
        #endregion

        #region 获取验证码图片
        /// <summary>
        /// 获取验证码图片
        /// </summary>
        /// <returns></returns>
        public IActionResult GetCaptchaImage()
        {
            string sessionId = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>().HttpContext.Session.Id;

            Tuple<string, int> captchaCode = CaptchaHelper.GetCaptchaCode();
            byte[] bytes = CaptchaHelper.CreateCaptchaImage(captchaCode.Item1);
            new SessionHelper().WriteSession("CaptchaCode", captchaCode.Item2);
            return File(bytes, @"image/jpeg");
        }
        #endregion

        #region 用户登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="captchaCode">验证码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DoLogin(string userName, string password, string captchaCode)
        {
            TData obj = new TData() { Msg = "登录成功" };
            var objnum = HttpContext.Session.GetString("errorCodeNum");
            var errorNum = 0;
            if (objnum != null) errorNum = int.Parse(objnum);
            errorNum += 1;
            if (errorNum >= 3)
            {
                if (captchaCode.IsEmpty())
                {
                    obj.Code = errorNum;
                    obj.Msg = "请输入验证码";
                    return Json(obj);
                }
                var objVcode = new SessionHelper().GetSession("CaptchaCode").ParseToString();
                if (!captchaCode.IsEmpty() && objVcode != captchaCode)
                {
                    obj.Code = errorNum;
                    obj.Msg = "请输入正确的验证码";
                    return Json(obj);
                }
            }
            //校验登录
            var userObj = await userService.CheckLogin(userName, password, (int)PlatformEnum.Web);
            if (userObj.MsgCode != MsgCode.Success)
            {
                //记录登录错误次数
                HttpContext.Session.SetString("errorCodeNum", errorNum.ToString());
                obj.Code = errorNum;
                obj.Msg = userObj.Msg;
                return Json(obj);
            }
            if (objnum.ParseToInt() >= 1)
            {
                HttpContext.Session.SetString("errorCodeNum", "0");
            }
            //保存token 修改用户保存token信息
            await userService.UpdateUser(userObj.Data);
            //存储用户信息
            await OperatorService.Instance.AddCurrent(userObj.Data.WebToken);
            //记录登录日志
            string ip = NetHelper.Ip;
            string browser = NetHelper.Browser;
            string os = NetHelper.GetOSVersion();
            string userAgent = NetHelper.UserAgent;

            Action taskAction = async () =>
            {
                LogLoginEntity logLoginEntity = new LogLoginEntity
                {
                    LogStatus = userObj.MsgCode == MsgCode.Success ? OperateStatusEnum.Success.ParseToInt() : OperateStatusEnum.Fail.ParseToInt(),
                    Remark = userObj.Msg,
                    IpAddress = ip,
                    IpLocation = IpLocationHelper.GetIpLocation(ip),
                    Browser = browser,
                    OS = os,
                    ExtraRemark = userAgent,
                    BaseCreatorId = userObj.Data?.Id,
                    UserName = userObj.Data?.UserName
                };

                //让底层不用获取HttpContext
                logLoginEntity.BaseCreatorId = logLoginEntity.BaseCreatorId ?? "0";

                await logLoginService.SaveForm(logLoginEntity);
            };
            AsyncTaskHelper.StartTask(taskAction);
            //解锁移除缓存
            var cache = CacheFactory.Cache.GetCache<OperatorInfo>("lockScreenUser_" + userObj.Data.Id);
            if (!cache.IsEmpty())
            {
                CacheFactory.Cache.RemoveCache("lockScreenUser_" + userObj.Data.Id);
            }
            //移除菜单缓存
            new MenuCache().Remove();
            return Json(obj);
        }
        #endregion
    }
}
